package logic

import (
	"context"
	"fmt"
	"super/model/mysql"
	"super/model/redisinit"
	"super/pkg"

	"super/superrpc/internal/svc"
	"super/superrpc/superrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *superrpc.UserLoginRequest) (*superrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	sendGet := redisinit.Rdb.Get("sendSmsLogIn" + in.Phone)
	if sendGet.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	captchaGet := redisinit.Rdb.Get("captchaLogIn" + in.Phone)
	if captchaGet.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该账号未注册,请前往注册")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,登录失败")
	}
	return &superrpc.UserLoginResponse{
		Id: int64(user.ID),
	}, nil
}
